package com.dcxs.shop.module.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dcxs.shop.common.utils.R;
import com.dcxs.shop.module.order.entity.JsCard;
import com.dcxs.shop.module.order.service.IJsCardService;
import com.dcxs.shop.module.user.entity.JsUsr;
import com.dcxs.shop.module.user.service.IJsUsrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zzh
 * @since 2020-03-01
 */
@RestController
@RequestMapping("/order/js-card")
public class JsCardController {

    @Autowired
    private IJsCardService cardService;

    @Autowired
    private IJsUsrService usrService;

    //兑换
    @RequestMapping("/exchangePoints")
    @Transactional(rollbackFor = Exception.class)
    public R exchangePoints(@RequestBody JsCard card, HttpServletRequest request){
        JsCard card1 = cardService.getOne(new QueryWrapper<JsCard>().eq("card_pass",card.getCardPass()).eq("state",0));
        if(null!=card1){
            JsUsr usr = usrService.getOne(new QueryWrapper<JsUsr>().eq("phone",request.getAttribute("userId")));
            card1.setUsrId(usr.getId());
            card1.setActiveDate(LocalDate.now());
            card1.setActiveTime(LocalDateTime.now());
            card1.setNickname(usr.getNickname());
            card1.setPhone(usr.getPhone());
            card1.setSex(usr.getSex());
            card1.setState(1);
            cardService.updateById(card1);
            usr.setBalance(usr.getBalance().add(card1.getFee()));
            usrService.updateById(usr);
            return R.ok();
        }
        return R.error("密码错误或者不存在");
    }

}
